package com.fubt.repeat;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fubt.repeat.token.impl.CookieTokenManager;
import com.fubt.repeat.util.TokenManagerHelper;

@Controller
@SpringBootApplication
public class App implements CommandLineRunner {

    public static final String DEFAULT_TOKEN_NAME = "myToken";

    @RequestMapping("test")
    String home() {
        return "test";
    }

    @RequestMapping("/createOrder")
    @ResponseBody

    public String createOrder(@RequestParam(value = "token", required = true) String token) {

        // 获取客户端传来的token
        String myToken = TokenManagerHelper.getTokenManager().get(DEFAULT_TOKEN_NAME);
        if (StringUtils.isBlank(myToken) || !StringUtils.equals(myToken, token)) {
            throw new RepeatException();

        }

        // 处理业务 ....

        // 移除token
        TokenManagerHelper.getTokenManager().remove(DEFAULT_TOKEN_NAME);
        return "ok";
    }

    @RequestMapping("/settingCookie")
    @ResponseBody

    public String settingCookie(HttpServletRequest request, HttpServletResponse response) {
        String token = getRandomStr();
        TokenManagerHelper.getTokenManager().add(DEFAULT_TOKEN_NAME, token);
        return token;
    }

    /**
     * 随机生成token
     * 
     * @return
     */
    private String getRandomStr() {
        String strs = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        Random random = new Random();
        String str = "";
        for (int i = 0; i < strs.length(); i++) {

            int index = random.nextInt(strs.length());
            str += strs.charAt(index);

        }
        return str;
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(App.class, args);
    }

    public void run(String... args) throws Exception {
        // token默认存放到Cookie
        TokenManagerHelper.setTokenManager(new CookieTokenManager());

    }
}
